// axios基础封装
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from 'element-plus'
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 100000
})
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  // 从pinia中获取token 
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  // 将token拼接到请求数据中
  if(token){
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))
// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  // 统一错误提示
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  // 401 token失效处理
  if(e.response.status === 401){
    const userStore = useUserStore()
    userStore.clearUserInfo()
    router.push({path: '/login'})
  }
  return Promise.reject(e)
})

export default httpInstance